﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Loader;
using System.Reflection;

namespace MEF2Test.ConsoleTest
{
	static class AddInsCatalog
	{
		// 路径。
		static string _path = Path.Combine(Environment.CurrentDirectory, "AddIns");

		/// <summary>
		/// 返回指定路径的程序集集合。
		/// </summary>
		/// <param name="path">指定路径。</param>
		/// <returns>程序集集合。</returns>
		public static IEnumerable<Assembly> GetAssembies(string filepath, Predicate<string> match)
		{
			var context = AssemblyLoadContext.Default;
			var queue = new Queue<string>();

			queue.Enqueue(filepath);

			while (queue.Count > 0)
			{
				var path = queue.Dequeue();

				foreach (var item in Directory.GetDirectories(path))
				{
					if (item.EndsWith("ref")) continue;
					queue.Enqueue(item);
				}

				foreach (var item in Directory.GetFiles(path))
				{
					if (item.EndsWith(".dll") && match(item))
					{
						context.LoadFromAssemblyPath(item);
					}
				}

			}

			
			return context.Assemblies;
		}

		/// <summary>
		/// 返回默认路径(AddIns文件夹)指定筛选程序集。
		/// </summary>
		/// <param name="match">筛选器。</param>
		/// <returns>程序集集合。</returns>
		public static IEnumerable<Assembly> GetAssembies(Predicate<string> match)
		{
			return GetAssembies(_path, match);
		}

		/// <summary>
		/// 返回默认路径(AddIns文件夹)指定程序集。
		/// </summary>
		/// <returns></returns>
		public static IEnumerable<Assembly> GetAssembies()
		{
			return GetAssembies(_path, (ass) => true);
		}

	}
}
